package com.jintoufs.web.action.hotel;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jintoufs.dao.QueryFilters;
import com.jintoufs.dao.QueryRule;
import com.jintoufs.domain.customer.Customer;
import com.jintoufs.domain.hotel.Hotel;
import com.jintoufs.domain.images.Images;
import com.jintoufs.domain.region.Region;
import com.jintoufs.logAnnotation.SystemControllerLog;
import com.jintoufs.service.hotel.HotelService;
import com.jintoufs.service.image.ImageService;
import com.jintoufs.service.region.RegionService;
import com.jintoufs.util.ztree.TreeNode;
import com.jintoufs.web.action.shiro.bind.annotation.CurrentUser;
import com.jintoufs.web.action.support.JqgridPage;
import com.jintoufs.web.action.support.SupportAction;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("hotel")
public class HotelAction extends SupportAction{
    @Resource
    private HotelService hotelService;

    @Resource
    private ImageService imageService;

    @Resource
    private RegionService regionService;

    @RequestMapping("list")
    public String list(Model model, @CurrentUser Customer customer) {
        Map<String,Object> params = new HashMap<>(1);
        params.put("customerId", customer.getId());
        List<Map<String,Object>> hotels = hotelService.queryByParams(params);
        model.addAttribute("hotelList", hotels);
        return "hotel/list-hotel";
    }

    @RequestMapping("/oper")
    @SystemControllerLog(description = "酒店")
    public void oper(HttpServletResponse response, String _id, String oper, Hotel hotel) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            if (oper.equals("del") && _id != null) {
                hotelService.delete(_id);

            } else {

                switch (oper) {
                    case "edit":
                        hotel.setStatus("0");
                        hotelService.update(hotel);
                        ajaxMsg.setCode("200");
                        ajaxMsg.setMessage("更新成功");
                        break;
                    case "add":
                        Hotel tmp = hotelService.add(hotel);
                        if (tmp == null) {
                            ajaxMsg.setCode("500");
                            ajaxMsg.setMessage("添加失败，酒店名重复");
                        } else {
                            ajaxMsg.setCode("200");
                            ajaxMsg.setMessage("添加成功");
                        }
                        break;
                    default:
                        ajaxMsg.setCode("500");
                        ajaxMsg.setMessage("操作代码错误！系统只提供增加/修改/删除功能。");
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode("500");
            if (e instanceof DuplicateKeyException) {
                ajaxMsg.setMessage("此酒店名已存在！");
            } else {
                ajaxMsg.setMessage("程序出错，请联系管理员！");
            }
        }
        writeInfo(response, JSON.toJSONString(ajaxMsg));
    }

    @RequestMapping("/delete")
    @SystemControllerLog(description = "删除酒店")
    public void delete(HttpServletResponse response, String[] id) {
        for (String _id : id) {
            hotelService.delete(_id);
        }
        writeInfo(response, JSON.toJSONString(new AjaxMsg()));
    }

    @RequestMapping("/query")
    @ResponseBody
    @SystemControllerLog(description = "获取酒店列表")
    public JqgridPage query(HttpServletResponse response, int page, int rows, String sidx, String sord, String filters) {
        PageHelper.startPage(page, rows);
        QueryFilters filters_;
        if (filters == null || filters.trim().isEmpty()) {
            filters_ = new QueryFilters();
        } else {
            filters_ = JSON.parseObject(filters, QueryFilters.class);
        }
        filters_.setSidx(sidx);
        filters_.setSord(sord);
        QueryRule queryRule = new QueryRule();
        queryRule.setField("h.status");
        queryRule.setOp("eq");
        queryRule.setData("1");
        filters_.getRules().add(queryRule);
        List<Map<String,Object>> list = hotelService.getByFilter(filters_);
        // 用PageInfo对结果进行包装
        PageInfo pageInfo = new PageInfo(list);
        return new JqgridPage(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getPageNum(),
                pageInfo.getList());
    }

    @RequestMapping("/room")
    @SystemControllerLog(description = "获取酒店房间列表")

    public String getRoom(String hotelId){
//        List<HotelRoom> hotelRooms = hotelService.getRoomList(hotelId);
//
//        model.addAttribute("hotelRooms",hotelRooms);

        return "redirect:/room/list?id=" +hotelId;
    }

    @RequestMapping("/edit")
    @SystemControllerLog(description = "进入酒店编辑界面")
    public String edit(Model model,String hotelId){
        Map<String,Object> param = new HashMap<>();
        param.put("id",hotelId);
        List<Map<String,Object>> hotel = hotelService.queryByParams(param);
        Region region = regionService.queryById(Short.valueOf(hotel.get(0).get("regionId").toString()));
        List<TreeNode> list = regionService.getModuleTree(region);
        model.addAttribute("ztreeNodes",JSON.toJSONString(list));
        model.addAttribute("hotel",hotel.get(0));
        model.addAttribute("title","编辑酒店");
        model.addAttribute("isEdit",true);
        return "/hotel/input";
    }


    @RequestMapping("/add")
    @SystemControllerLog(description = "进入酒店新增界面")
    public String add(Model model){
        List<TreeNode> list = regionService.getModuleTree(null);
        model.addAttribute("ztreeNodes",JSON.toJSONString(list));
        model.addAttribute("title","新增酒店");
        model.addAttribute("isEdit",false);
        return "/hotel/input";
    }


    @RequestMapping(value = "/images")
    @SystemControllerLog(description = "进入酒店图片管理界面")
    public String toManageImg(String hotelId,Model model) {
        Map<String,Object> params = new HashMap<>();
        params.put("valueId", hotelId);
        List<Images> images = imageService.selectByparams(params);
        model.addAttribute("images", images);
        model.addAttribute("hotelId", hotelId);
        return "/images/images";
    }


    @RequestMapping(value="/save",method = RequestMethod.POST)
    @ResponseBody
    public  AjaxMsg save(Hotel hotel,@CurrentUser Customer customer,String imgUrl){
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            String id = getUUID();
            hotel.setStatus("0");
            hotelService.save(hotel,id,customer);
            if(imgUrl!=null){
                Images images = new Images();
                images.setId(getUUID());
                images.setPath(imgUrl);
                images.setCreateTime(new Date());
                images.setValueId(id);
                images.setCover("1");
                imageService.insert(images);
            }
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setMessage("添加失败");
            ajaxMsg.setCode(AjaxMsg.FAILURE);
        }

        return ajaxMsg;
    }
}
